package com.bite.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.bite.demo.Dao.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@Controller
public class captchaController {
    @Autowired
    private CaptchaProperties captchaProperties;

    private final static long VALID_MILLIS_TIME = 60 * 1000;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            lineCaptcha.write(response.getOutputStream());
            session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());
            System.out.println("生成验证码" + lineCaptcha.getCode());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @ResponseBody
    @RequestMapping("/check")
    public Boolean checkHomeCaptcha(String captcha, HttpSession session){
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        String savedCaptcha = (String)session.getAttribute(captchaProperties.getSession().getKey());
        Date sessionDate = (Date)session.getAttribute(captchaProperties.getSession().getDate());
        if(captcha.equalsIgnoreCase(savedCaptcha)){
            if(sessionDate == null || System.currentTimeMillis() - sessionDate.getTime() < VALID_MILLIS_TIME){
                return true;
            }
            return false;
        }
        return false;
    }
}
